<template>
  <div v-loading="loading" class="course-content">
    <div v-if="!haveUnitTestEnd" style="margin-bottom: 10px;">
      <el-button
        type="primary"
        :disabled="haveUnitTestEnd"
        @click="addCourseTest"
      >
        添加课程测试题
      </el-button>
    </div>
    <div
      v-for="(item, index) in sectionData"
      :key="item.id"
      class="course-content__section"
    >
      <div class="course-content__section--title embellish">
        <div class="left">
          <span class="bold">
            {{ `第${arabicNumToChineseNumber(index + 1)}章` }}
          </span>
          <span class="bold" style="margin-left: 10px">{{ item.name }}</span>
        </div>

        <template v-if="!item.unitTest">
          <el-button
            :disabled="!!item.unitTest"
            type="text"
            icon="el-icon-plus"
            @click="openCreateTestDialog(item)"
          >
            添加章节小测
          </el-button>
        </template>
      </div>
      <div
        v-for="(content, cIndex) in item.duration"
        :key="content.id"
        class="course-content__section--duration embellish"
      >
        <div>
          <i class="bold dot">●</i>
          <span class="mf">{{ `${index + 1}.${cIndex + 1}` }}</span>
        </div>
        <div class="title mf"> {{ content.name }} </div>

        <div class="video-duration mf"> {{ content.course_duration }} </div>
        <div class="video-play mf" @click="handelVideoPlay(item, content)">
          <i class="el-icon-video-play" />
        </div>
      </div>
    </div>

    <el-dialog
      width="35%"
      :title="videoPlayer.title"
      :close-on-click-modal="false"
      :visible.sync="videoPlayer.visible"
      :before-close="handlePlayerDialogClose"
      :destroy-on-close="true"
      append-to-body
    >
      <video
        ref="video-player"
        style="max-height: 65vh"
        controls
        class="video"
        :src="videoPlayer.path"
        preload="none"
      />
    </el-dialog>

    <CreateTestDialog
      ref="createTestDialogRef"
      v-model="testDialogShow"
      @onConfirm="createTestConfirm"
    />

  </div>
</template>
<script>
import CreateTestDialog from './CreateTestDialog.vue'
import { arabicNumToChineseNumber } from '@/utils'
import { createCourseTest } from '@/api/v2/course'
export default {
  name: '',
  components: {
    CreateTestDialog
  },
  props: {
    sectionData: {
      type: Array,
      default: () => ([])
    },
    courseId: {
      type: [Number, String],
      default: null
    },
    haveUnitTestEnd: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      videoPlayer: {
        visible: false,
        title: '',
        path: ''
      },
      testDialogShow: false,
      params: {
        chapter_id: null
      },
      isCreateCourseTest: false,
      loading: false
    }
  },
  created() {
    this.init()
  },
  methods: {

    async init() {
      try {
        this.loading = true
        await this.sleep(400)
        this.$emit('refresh')
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },

    arabicNumToChineseNumber,

    openCreateTestDialog(row) {
      console.log('row --------->', row)
      this.isCreateCourseTest = false
      this.params.chapter_id = row.id
      this.testDialogShow = true
      this.resetFields()
    },

    addCourseTest() {
      this.isCreateCourseTest = true
      this.testDialogShow = true
      this.resetFields()
    },

    resetFields() {
      this.$refs?.createTestDialogRef?.resetFields()
    },

    handelVideoPlay(item, content) {
      this.videoPlayer.path = content.path
      this.videoPlayer.title = `${item.name} -- ${content.name}`
      this.videoPlayer.visible = true
    },

    handlePlayerDialogClose() {
      this.videoPlayer.visible = false
      this.$refs['video-player']?.pause?.()
    },

    generateParams(data) {
      const { pass_rate, data: topic, test_title } = data

      // 创建课程测试
      if (this.isCreateCourseTest) {
        return {
          course_id: this.courseId,
          test_title,
          pass_rate,
          data: JSON.stringify(this.topicFormatter(topic))
        }
      }

      // 创建章节测试
      return {
        ...this.params,
        test_title,
        pass_rate,
        data: JSON.stringify(this.topicFormatter(topic))
      }
    },

    createTestConfirm(e) {
      console.log('e --------->', e)
      const params = this.generateParams(e)
      this.createCourseTest(params)
    },

    topicFormatter(data) {
      return data.map(v => {
        return {
          ...v,
          answer: JSON.stringify(v.answer)
        }
      })
    },

    async createCourseTest(data) {
      try {
        const res = await createCourseTest(data)
        console.log('res --------->', res)
        if (res.code === 200) {
          this.$message.success('测试题创建成功')
        }
        this.reset()
        this.init()
      } catch (error) {
        this.$message.error('测试题添加失败')
      }
    },

    reset() {
      this.params = { chapter_id: null }
      this.isCreateCourseTest = false
    }
  }
}
</script>
<style lang="scss" scoped>
.course-content {
  &__section {

    &--title {
      padding: 10px;
      display: flex;
      align-items: center;
      .left {
        font-size: 16px;
        flex: 1;
      }
    }

    &--duration {
      display: flex;
      padding: 10px 25px;
      color: #888;
      font-weight: normal;
      .dot {
        font-size: 16px;
      }

      .video-duration {
        flex: 1;
      }

      .title {
        width: 400px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

  }

  .embellish {
    border-bottom: 1px solid #f5f5f5;
    &:hover {
      background-color: #f5f5f5;
    }
  }

  .bold {
    font-weight: bold;
  }
  .mf {
    margin-left: 10px;
  }
}
.video {
  width: 100%;
}
</style>
